package com.lwj.test.netty;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class ClientPool
{
    public static ClientPool clientPool = new ClientPool();
    
    private ClientBootstrap bootstrap;
    
    private ClientPool()
    {
        bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), 
                Executors.newCachedThreadPool()));
        
        bootstrap.setPipelineFactory(new ClientPipelineFactory());
        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);
    }
    
    public static ClientPool getInstance()
    {
        return clientPool;
    }
    
    public void getChannelFuture(String host, int port, String message)
    {
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
        		port));
        future.awaitUninterruptibly();
        if (!future.isSuccess())
        {
            future.getCause().printStackTrace();
            future.getChannel().getCloseFuture().awaitUninterruptibly(); 
            return;
        }
        future.getChannel().write(message);
    }
    
    public static void main(String[] args) throws InterruptedException
    {
        for (int i = 0; i < 1000; i++)
        {
            ClientPool.getInstance().getChannelFuture("192.168.5.124", 
            		8980,
                    "test" + i);
            Thread.sleep(1000);
        }
    }
}
